package Imp.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.apache.seata.tm.api.GlobalTransactionContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Arrays;
import java.util.List;

@Slf4j
@Configuration
public class FeignConfig {
    private static final List<String> IGNORE_PATHS = Arrays.asList(
            "/third/api/get/fallbackStock" // 不想让 Seata 事务管理的路径
    );
    @Bean
    public RequestInterceptor requestInterceptor() {
        return template -> {
            //排除openFeign
            String url = template.url();
            log.info("url:{}", url);
            if (IGNORE_PATHS.stream().anyMatch(url::startsWith)) {
                log.info("忽略seata:{}", IGNORE_PATHS);
                return;
            }
            // 获取当前事务的 XID（事务ID）
            String xid = GlobalTransactionContext.getCurrent().getXid();

            if (xid != null) {
                // 在请求头中传递 xid，Seata 会通过这个 xid 来关联事务
                template.header("TX_XID", xid);
            }
        };
    }
}
